<template>
<div class="button">
          <el-upload
      class="upload-demo"
      action
      accept=".xlsx, .xls"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="handleChange"
      >
      <el-button type="primary">导入Excel</el-button>
      <template #tip>
       
      </template>
  </el-upload>
  <el-button type="success" @click="aotuSbmi">导出Excel</el-button>
</div>

<el-table :data="dataLIst" style="width: 100%">
    <el-table-column prop="name" label="姓名" width="180" />
    <el-table-column prop="phone" label="手机号" width="180" />
  </el-table>
</template>

<script setup lang="ts">
import {readFile,character} from '@/utils/component/fun.ts'
import {read,utils,writeFile} from 'xlsx'
import {ref} from 'vue'
const dataLIst = ref([])
const handleChange = async (file: any) =>{
    // 读取file.raw中的内容
    const filerew = file.raw;
    if(!filerew) return
    const result = await readFile(filerew);
    const workbook = read(result, { type: 'binary' }),
    worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const data = utils.sheet_to_json(worksheet);
    console.log(data);
    // 处理workbook
    const arr:any = []
  data.forEach((item:any) => {
    const obj = {}
    
    for(let key in character) {

      if(!character.hasOwnProperty(key))break
      let v = character[key],
      text = v.text,
      type = v.type
      v = item[text] || "";
      console.log(text);
      
      type === "string" ? v = String(v) : null;
      type === "number" ? v = Number(v) : null;
      console.log(v);
      obj[key] = v
    }
    arr.push(obj)
    console.log(arr);
    
    
  });
  dataLIst.value = arr
  
}
// 导出
const aotuSbmi = ()=>{
  const arrrdata = dataLIst.value.map((item:any,index)=>{
    return{
      编号:index+1,
      姓名:item.name,
      手机号:item.phone
    }
  })
  console.log(arrrdata);
  const sheet = utils.json_to_sheet(arrrdata),
  book = utils.book_new();
  utils.book_append_sheet(book, sheet, 'sheet1'); 
  writeFile(book,`user${new Date().getTime()}.xlsx`)
  
}


</script>

<style scoped>
.button{
  display: flex;
  justify-content: space-around;

}
</style>